import React, { useState, useRef, useEffect } from 'react';
import { Space, Table, Tag, Modal, Button, message } from 'antd';
import { AudioOutlined } from '@ant-design/icons';
import { Input } from 'antd';
import { DeleteOutlined, EditOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import Userfrom from '../../components/userfrom/index'
import './user.scss'
import dayjs from 'dayjs'
import { getUsers, deleteUser, editUser, addUser } from "../../api/user";
export default function Usermannge() {
    const { Search } = Input;
    const [messageApi, contextHolder] = message.useMessage();
    const [size, setSize] = useState('large'); 
    const { confirm } = Modal
    const [userdata, setUser] = useState([])
    const [Searchdata, setSearch] = useState([])
    const [deletedata, setdeleteUser] = useState([])
    const [editdata, seteditUser] = useState([])
    const [editid, seteditUserID] = useState([])
    const [adddata, setaddUser] = useState([])
    const [dataSource, setdataSource] = useState([])
    const [isAddVisible, setisAddVisible] = useState(false)
    const [isUpdateVisible, setisUpdateVisible] = useState(false)
    const [roleList, setroleList] = useState([])
    const [regionList, setregionList] = useState([])
    const [current, setcurrent] = useState(null)
    const [isUpdateDisabled, setisUpdateDisabled] = useState(false)
    const AddForm = useRef(null)
    const UpdateForm = useRef(null)
    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            key: 'id',
        },
        {
            title: '账号',
            dataIndex: 'nickName',
            key: 'nickName',
            render: (text) => <h3>{text}</h3>,
        },
        {
            title: '密码',
            dataIndex: 'nickName',
            key: 'nickName',
            render: (text) => <h3>******</h3>,
        },
        {
            title: '姓名',
            dataIndex: 'title',
            key: 'title',
            render: (text) => <h3>{text}</h3>,
        },
        {
            title: '性别',
            key: 'sex',
            dataIndex: 'sex',
            render: (sex) => {
                let colors = sex === 1 ? 'geekblue' : 'green';
                let sexs = '';
                if (colors === 'geekblue') {
                    sexs = '男'
                } else {
                    sexs = '女'
                }
                return (
                    <Tag color={colors}>
                        {sexs}
                    </Tag>
                );
            },
        },
        {
            title: '地址',
            key: 'addr',
            dataIndex: 'addr',
        },
        {
            title: '新增时间',
            dataIndex: 'birth2',
            key: 'birth2',
        },
        {
            title: '修改时间',
            dataIndex: 'birth3',
            key: 'birth3',
        },
        {
            title: "操作",
            render: (item) => {
                return <div>
                <Button danger icon={<DeleteOutlined />} onClick={() => confirmMethod(item)}>删除</Button>
                <Button type="primary" icon={<EditOutlined />} disabled={item.default} onClick={() => handleUpdate(item)} >修改</Button>
              </div>
            }
        }
    ];
    const confirmMethod = (item) => {
        confirm({
            title: '你确定要删除?',
            icon: <ExclamationCircleOutlined />,
            onOk() {
                deleteMethod(item)
            },
            onCancel() {
            },
        });
    }
    const handleUpdate = (item) => {
        setisUpdateVisible(true)
        setTimeout(() => {
            const { birth, birth2, birth3, id } = item;
            item.birth = dayjs(birth);
            item.birth2 = dayjs(birth2);
            item.birth3 = dayjs(birth3);
            setregionList(item.birth);
            setregionList(item.birth2);
            setregionList(item.birth3);
            seteditUserID(id)
            UpdateForm.current.setFieldsValue(item);
        }, 100)
        setcurrent(item)
    }
    const handleChange = (item) => {
        setdataSource([...dataSource])
    }
    const getuserdatas = async () => {
        const result = await getUsers()
        const { users } = result.data;
        console.log(users);
        setUser(users)
    }
    useEffect(() => {
        getuserdatas()
    }, [])
    const deleteMethod = (item) => {
        const { id, role, patientindex } = item;
        deleteUser({ id }).then(res => {
            message.success("删除成功")
            getuserdatas()
        })
        var a = setdataSource(dataSource.filter(data => data.id !== item.id))
    }
    const handleAudit = (item) => {
    }
    const updateFormOK = () => {
        var a = UpdateForm.current.validateFields().then(value => {
            var b = userdata.map(v => v.title).indexOf(value.title);
            value.id = editid;
            editUser(value).then((response) => {
                getuserdatas()
                message.success('修改成功！')
            }).catch(e => {
                message.error('修改失败！')
            })
            setisUpdateVisible(false)
            setdataSource(dataSource.map(item => {
                if (item.id === current.id) {
                    return {
                        ...item,
                        ...value,
                        role: roleList.filter(data => data.id === value.roleId)[0]
                    }
                }
                return item
            }))
            setisUpdateDisabled(!isUpdateDisabled)
        })
    }
    const addFormOK = () => {
        AddForm.current.validateFields().then(value => {
            const { birth } = value;
            value.birth = birth.format('YYYY-MM-DD');
            console.log(value);
            if (userdata.map(v => v.title).indexOf(value.title) != -1) {
                message.error("用户名已存在")
            } else {
                value.id = ++userdata.length
                setisAddVisible(false)
                AddForm.current.resetFields()
                addUser(value).then((response) => {
                    message.success("添加成功!")
                    getuserdatas()
                }).catch(e => {
                    message.success("添加失败,请重试!")
                })
            }
        }).catch(err => {
            console.log(err)
        })
    }
    const suffix = (
        <AudioOutlined
            style={{
                fontSize: 16,
                color: '#1890ff',
            }}/>
    );
    const onSearch = (value) => {
        let arr = [];
        setSearch(value)
        if (value) {
            arr = userdata.filter((data) => {
                return data.title.indexOf(value.toString()) !== -1;
            });
        } else {
            arr = userdata;
        }
        userdata.length = arr.length;
        setUser(arr)
        if (!value) {
            getuserdatas()
        }
    };
    const getdata = (value) => {
        if (!value.target.value) {
            getuserdatas()
        }
    }
    return (
        <div>
            <div className="spacewidth">
                <Button onClick={() => {
                    setisAddVisible(true)
                }} type="primary" size={size}>新增</Button>
                <Search size="large" placeholder="请输入用户名" style={{ width: 200 }} onChange={getdata} onSearch={onSearch} enterButton />
            </div>
            <Table columns={columns} dataSource={userdata}
                pagination={{
                    pageSize: 5
                }}
                rowKey={item => item.id} />
            <Modal
                open={isUpdateVisible}
                title="更新用户"
                okText="更新"
                cancelText="取消"
                onCancel={() => {
                    setisUpdateVisible(false)
                    setisUpdateDisabled(!isUpdateDisabled)
                }}
                onOk={() => updateFormOK()}>
                <Userfrom regionList={regionList} roleList={roleList} ref={UpdateForm} isUpdateDisabled={isUpdateDisabled} isUpdate={true}></Userfrom>
            </Modal>
            <Modal
                open={isAddVisible}
                title="添加用户"
                okText="确定"
                cancelText="取消"
                onCancel={() => {
                    setisAddVisible(false)
                }}
                onOk={() => addFormOK()}>
                <Userfrom regionList={regionList} roleList={roleList} ref={AddForm}></Userfrom>
            </Modal>
        </div>
    )
}
